package com.ibpd.shopping.assist;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.jsoup.helper.StringUtil;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.shopping.entity.AccountEntity;
import com.ibpd.shopping.service.account.AccountServiceImpl;
import com.ibpd.shopping.service.account.IAccountService;

public class InterfaceUtil {

	public static final String LOGINEDUSERACCOUNT="LoginedUserAccount";
	public static final String LOGINEDUSERNICKNAME="LoginedUserNickname";
	public static final String LOGINEDUSERENTITY="LoginedUserEntity";
	public  static void setLoginUserInfoToSession(HttpSession session,AccountEntity acc){
		if(acc==null){
			session.removeAttribute(LOGINEDUSERACCOUNT);
			session.removeAttribute(LOGINEDUSERNICKNAME);
			session.removeAttribute(LOGINEDUSERENTITY);
		}else{
			session.setAttribute(LOGINEDUSERACCOUNT, acc.getAccount());
			session.setAttribute(LOGINEDUSERNICKNAME, acc.getNickname());
			session.setAttribute(LOGINEDUSERENTITY, acc);
		}
	}
	public static AccountEntity getLoginedAccountInfo(HttpServletRequest rq){
		HttpSession session=rq.getSession();
		Object obj=session.getAttribute(LOGINEDUSERENTITY);
		if(obj==null){
			if(rq.getParameter("userId")==null){
				return null;
			}else{
				IAccountService as=(IAccountService) ServiceProxyFactory.getServiceProxy(AccountServiceImpl.class);
				String userId=rq.getParameter("userId");
				if(StringUtil.isNumeric(userId)){
					AccountEntity ae=as.getEntityById(Long.valueOf(userId));
					return ae;
				}
				
				return null;
			}
		}
		if(obj instanceof AccountEntity)
			return (AccountEntity) obj;
		else{
			return null;
		}
			
	}
	public static void swap(Object formAcc,Object dbAcc) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Method[] methods=formAcc.getClass().getMethods();
		for(Method getMethod:methods){
			String getMethodName=getMethod.getName();
			if(getMethodName.substring(0,3).equals("get") && !getMethodName.equals("getClass")){
				String setMethodName="set"+getMethodName.substring(3);
				Method[] dbmthods=dbAcc.getClass().getMethods();
				Method setMethod=null;
				for(Method m:dbmthods){
					if(m.getName().equals(setMethodName)){
						setMethod=m;
					}
				}
				//Method setMethod=dbAcc.getClass().getMethod(setMethodName, getMethod.getReturnType());
				if(setMethod!=null){
					setMethod.invoke(dbAcc, getMethod.invoke(formAcc, null));
				}
			}
		}
	}

}
